package com.twu.biblioteca;

import java.io.*;

public class Gateway extends MenuList{
    String menuName = "Login";
    private InputHandler inputHandler;
    private String username;
    private String password;
    public boolean status;
    private File dataFile = new File("src/com/twu/biblioteca/user.txt");
    private File logFile = new File("src/com/twu/biblioteca/current.txt");

    public Gateway(){
        inputHandler = new InputHandler();
        username = "";
        password = "";
        status = false;
    }

    public boolean execute() throws IOException {
        if(menuName.equals("Login")){
            System.out.print("\nUsername: ");
            username = inputHandler.readSingleString();

            System.out.print("\nPassword: ");
            password = inputHandler.readSingleString();

            if(isValidLoginCredentials(username,password)) {
                status = true;
                menuName = "Logout";
                return status;
            }
            else {
                status = false;
                username = "";
                password = "";
                return status;
            }
        }
        else{
            BufferedWriter fileWriter = new BufferedWriter(new FileWriter(logFile));
            fileWriter.write("");
            fileWriter.close();
            return true;
        }
    }

    public boolean isValidLoginCredentials(String username,String password) throws IOException {
        BufferedReader fileReader = new BufferedReader(new FileReader(dataFile));
        BufferedWriter fileWriter;

        String dataLine;

        while((dataLine = fileReader.readLine())!=null) {
            String[] tempUserInfo = dataLine.split(" ");
            if(tempUserInfo[0].equals(username) && tempUserInfo[1].equals(password)) {
                fileWriter = new BufferedWriter(new FileWriter(logFile));
                fileWriter.write(dataLine);
                fileWriter.close();
                return true;
            }
        }
        return false;
    }

    public String getMenuName() {
        return menuName;
    }

}
